<template>
  <div class="unqualified-page">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <el-page-header :content="['质检管理', '不合格品处理']" />
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        @click="handleBatchDelete"
        :disabled="selectedIds.length === 0"
      >
        批量删除（{{ selectedIds.length }}）
      </el-button>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="100px" size="medium">
        <el-form-item label="工单编号">
          <el-input 
            v-model="searchForm.produceCode" 
            placeholder="请输入" 
            clearable
            style="width: 180px;"
          />
        </el-form-item>
        <el-form-item label="物料群组">
          <el-select 
            v-model="searchForm.materialGroupId" 
            placeholder="全部" 
            clearable
            style="width: 180px;"
          >
            <el-option label="全部" value="" />
            <el-option 
              v-for="group in materialGroups" 
              :key="group.id" 
              :label="group.materialGroupName" 
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select 
            v-model="searchForm.handleStatus" 
            placeholder="全部" 
            clearable
            style="width: 180px;"
          >
            <el-option label="全部" value="" />
            <el-option label="待处理" value="0" />
            <el-option label="已返工" value="1" />
            <el-option label="已报废" value="2" />
            <el-option label="让步接收" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="质检时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchUnqualifiedData">查询</el-button>
          <el-button @click="resetSearch" style="margin-left: 8px;">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 不合格品列表 -->
    <el-card shadow="hover">
      <el-table 
        :data="unqualifiedList" 
        border 
        stripe
        v-loading="tableLoading"
        element-loading-text="加载中..."
        @selection-change="handleSelectionChange"
        style="width: 100%;"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="inspectionNumber" label="质检编号" width="150" />
        <el-table-column prop="produceCode" label="生产工单编号" width="150" />
        <el-table-column prop="produceName" label="生产工单名称" width="180" />
        <el-table-column prop="materialGroupName" label="物料群组" width="180" />
        <el-table-column prop="inspectedQuantity" label="检验数量" width="120" />
        <el-table-column prop="qualifiedQuantity" label="合格数量" width="120">
          <template #default="scope">
            <span style="color: #FF9800;">{{ scope.row.qualifiedQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unqualifiedQuantity" label="不合格数量" width="120">
          <template #default="scope">
            <span style="color: #FF5252; font-weight: bold;">{{ scope.row.unqualifiedQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="处理状态" width="130">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.handleStatus)">
              {{ getStatusText(scope.row.handleStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="处理人" width="120" />
        <el-table-column prop="handleTime" label="处理时间" width="180">
          <template #default="scope">
            {{ scope.row.handleTime ? formatDate(scope.row.handleTime) : '未处理' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="openHandleDialog(scope.row)"
              :disabled="scope.row.handleStatus !== '0'"
            >
              处理
            </el-button>
            <el-button link type="info" @click="openDetailDialog(scope.row)">详情</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 处理弹窗 -->
    <el-dialog 
      v-model="handleDialogVisible" 
      title="不合格品处理" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="handleFormRef" 
        :model="handleForm" 
        :rules="handleRules" 
        label-width="120px"
        size="medium"
      >
        <el-form-item label="质检编号">
          <el-input v-model="handleForm.inspectionNumber" disabled />
        </el-form-item>
        <el-form-item label="工单信息">
          <el-input 
  :value="`${handleForm.produceCode}（${handleForm.produceName}）`" 
  disabled 
/>
        </el-form-item>
        <el-form-item label="不合格数量">
          <el-input 
            v-model="handleForm.unqualifiedQuantity" 
            disabled 
            style="color: #FF5252;"
          />
        </el-form-item>
        <el-form-item label="处理方式" prop="handleStatus">
          <el-radio-group v-model="handleForm.handleStatus">
            <el-radio label="1">返工</el-radio>
            <el-radio label="2">报废</el-radio>
            <el-radio label="3">让步接收</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理说明" prop="handleDesc">
          <el-input
            v-model="handleForm.handleDesc"
            type="textarea"
            rows="3"
            placeholder="请输入处理说明（如返工方案、报废原因等）"
          />
        </el-form-item>
        <el-form-item label="处理人">
          <el-input v-model="handleForm.handler" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandleForm">确认处理</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="不合格品详情" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-descriptions column="2" border>
        <el-descriptions-item label="质检编号">{{ detailForm.inspectionNumber }}</el-descriptions-item>
        <el-descriptions-item label="工单ID">{{ detailForm.productionOrderId }}</el-descriptions-item>
        <el-descriptions-item label="工单编号">{{ detailForm.produceCode }}</el-descriptions-item>
        <el-descriptions-item label="工单名称">{{ detailForm.produceName }}</el-descriptions-item>
        <el-descriptions-item label="物料群组">{{ detailForm.materialGroupName }}</el-descriptions-item>
        <el-descriptions-item label="质检人员">{{ detailForm.inspector }}</el-descriptions-item>
        <el-descriptions-item label="质检时间">{{ formatDate(detailForm.inspectionTime) }}</el-descriptions-item>
        <el-descriptions-item label="检验数量">{{ detailForm.inspectedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="合格数量">{{ detailForm.qualifiedQuantity }}</el-descriptions-item>
        <el-descriptions-item label="不合格数量">
          <span style="color: #FF5252;">{{ detailForm.unqualifiedQuantity }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="处理状态" :span="2">
          <el-tag :type="getStatusTagType(detailForm.handleStatus)">
            {{ getStatusText(detailForm.handleStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人" v-if="detailForm.handleStatus !== '0'">{{ detailForm.handler }}</el-descriptions-item>
        <el-descriptions-item label="处理时间" v-if="detailForm.handleStatus !== '0'">
          {{ formatDate(detailForm.handleTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理说明" :span="2" v-if="detailForm.handleStatus !== '0'">
          {{ detailForm.handleDesc || '无' }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

// axios.defaults.baseURL = 'http://localhost:5042';
const pinia = useCounterStore();

// 筛选表单
const searchForm = reactive({
  produceCode: '',
  materialGroupId: '',
  handleStatus: '',
  dateRange: [] as string[]
});

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表格数据与状态
const unqualifiedList = ref<any[]>([]);
const tableLoading = ref(false);
const selectedIds = ref<number[]>([]);

// 物料群组列表（从API结果提取）
const materialGroups = ref<any[]>([]);

// 处理弹窗相关
const handleDialogVisible = ref(false);
const handleFormRef = ref<FormInstance>();
const handleForm = reactive({
  id: 0,
  inspectionNumber: '',
  produceCode: '',
  produceName: '',
  unqualifiedQuantity: 0,
  handleStatus: '1', // 1-返工，2-报废，3-让步接收
  handleDesc: '',
  handler: pinia.piniaDto.realName || '未知用户'
});

// 处理表单验证规则
const handleRules = reactive<FormRules>({
  handleStatus: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  handleDesc: [
    { required: true, message: '请输入处理说明', trigger: 'blur' },
    { min: 5, message: '处理说明至少5个字符', trigger: 'blur' }
  ]
});

// 详情弹窗相关
const detailDialogVisible = ref(false);
const detailForm = reactive<any>({});

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// 根据处理状态获取标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '0': return 'warning'; // 待处理
    case '1': return 'success'; // 已返工
    case '2': return 'danger';  // 已报废
    case '3': return 'info';   // 让步接收
    default: return 'default';
  }
};

// 根据处理状态获取文本
const getStatusText = (status: string) => {
  switch (status) {
    case '0': return '待处理';
    case '1': return '已返工';
    case '2': return '已报废';
    case '3': return '让步接收';
    default: return '未知';
  }
};

// 重置筛选条件
const resetSearch = () => {
  searchForm.produceCode = '';
  searchForm.materialGroupId = '';
  searchForm.handleStatus = '';
  searchForm.dateRange = [];
  pagination.currentPage = 1;
  fetchUnqualifiedData();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchUnqualifiedData();
};

// 页码变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchUnqualifiedData();
};

// 处理表格选择变化
const handleSelectionChange = (val: any[]) => {
  selectedIds.value = val.map(item => item.id);
};

// 获取不合格品数据（核心方法）
const fetchUnqualifiedData = async () => {
  tableLoading.value = true;
  try {
    // 1. 调用API获取数据（按分页）
    const response = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
      params: {
        Index: pagination.currentPage,
        Size: pagination.pageSize,
        materialGroupId: searchForm.materialGroupId
      }
    });

    if (response.data.code !== 200) throw new Error('获取数据失败');
    let data = response.data.data.totalPage || [];

    // 2. 处理数据：添加处理状态字段（默认0-待处理）
    data = data.map((item: any) => ({
      ...item,
      handleStatus: item.handleStatus || '0', // 前端默认值
      handler: item.handler || '',
      handleTime: item.handleTime || '',
      handleDesc: item.handleDesc || '',
      inspectionDate: moment(item.inspectionTime).format('YYYY-MM-DD')
    }));

    // 3. 筛选不合格记录（unqualifiedQuantity>0）
    data = data.filter((item: any) => item.unqualifiedQuantity > 0);

    // 4. 前端二次筛选
    data = data.filter((item: any) => {
      // 工单编号模糊匹配
      if (searchForm.produceCode && !item.produceCode.includes(searchForm.produceCode)) return false;
      // 处理状态筛选
      if (searchForm.handleStatus && item.handleStatus !== searchForm.handleStatus) return false;
      // 时间范围筛选
      if (searchForm.dateRange.length === 2) {
        const itemDate = item.inspectionDate;
        const start = searchForm.dateRange[0];
        const end = searchForm.dateRange[1];
        if (itemDate < start || itemDate > end) return false;
      }
      return true;
    });

    // 5. 提取物料群组列表
    const groupSet = new Set<any>();
    data.forEach((item: any) => {
      if (item.materialGroupId && item.materialGroupName) {
        groupSet.add({ id: item.materialGroupId, materialGroupName: item.materialGroupName });
      }
    });
    materialGroups.value = Array.from(groupSet);

    // 6. 赋值数据
    unqualifiedList.value = data;
    pagination.total = response.data.data.totalcount; // 总数据量（未筛选前）

  } catch (error) {
    ElMessage.error(`加载失败: ${(error as Error).message || '未知错误'}`);
    console.error(error);
  } finally {
    tableLoading.value = false;
  }
};

// 打开处理弹窗
const openHandleDialog = (row: any) => {
  handleForm.id = row.id;
  handleForm.inspectionNumber = row.inspectionNumber;
  handleForm.produceCode = row.produceCode;
  handleForm.produceName = row.produceName;
  handleForm.unqualifiedQuantity = row.unqualifiedQuantity;
  handleForm.handleStatus = '1'; // 默认返工
  handleForm.handleDesc = '';
  handleDialogVisible.value = true;
};

// 提交处理表单（核心：通过Update API附加处理字段）
const submitHandleForm = async () => {
  if (!handleFormRef.value) return;
  
  await handleFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({ text: '处理中...' });
      try {
        // 1. 获取原记录完整数据（确保不丢失其他字段）
        const originResponse = await axios.get('/api/QualityInspection/QualityInspectionQuery', {
          params: { Index: 1, Size: 1, id: handleForm.id }
        });
        if (originResponse.data.code !== 200) throw new Error('获取原记录失败');
        const originData = originResponse.data.data.totalPage[0] || {};

        // 2. 构造更新参数（附加处理相关字段）
        const updateParams = {
          ...originData,
          id: handleForm.id,
          handleStatus: handleForm.handleStatus,
          handleDesc: handleForm.handleDesc,
          handler: handleForm.handler,
          handleTime: new Date().toISOString() // 处理时间
        };

        // 3. 调用更新API
        const response = await axios.put('/api/QualityInspection/UpdateQualityInspection', updateParams);
        if (response.data.code === 200) {
          ElMessage.success('处理成功');
          handleDialogVisible.value = false;
          fetchUnqualifiedData(); // 刷新列表
        } else {
          ElMessage.error(`处理失败: ${response.data.message || '未知错误'}`);
        }
      } catch (error) {
        ElMessage.error(`处理失败: ${(error as Error).message || '网络异常'}`);
        console.error(error);
      } finally {
        loading.close();
      }
    }
  });
};

// 打开详情弹窗
const openDetailDialog = (row: any) => {
  detailForm.id = row.id;
  detailForm.inspectionNumber = row.inspectionNumber;
  detailForm.productionOrderId = row.productionOrderId;
  detailForm.produceCode = row.produceCode;
  detailForm.produceName = row.produceName;
  detailForm.materialGroupName = row.materialGroupName;
  detailForm.inspectedQuantity = row.inspectedQuantity;
  detailForm.qualifiedQuantity = row.qualifiedQuantity;
  detailForm.unqualifiedQuantity = row.unqualifiedQuantity;
  detailForm.inspector = row.inspector;
  detailForm.inspectionTime = row.inspectionTime;
  detailForm.handleStatus = row.handleStatus;
  detailForm.handler = row.handler;
  detailForm.handleTime = row.handleTime;
  detailForm.handleDesc = row.handleDesc;
  detailDialogVisible.value = true;
};

// 单条删除
const handleDelete = (id: number) => {
  ElMessageBox.confirm(
    '确定要删除该不合格品记录吗？删除后无法恢复。',
    '删除确认',
    { type: 'warning' }
  ).then(async () => {
    try {
      const response = await axios.delete('/api/QualityInspection/DeleteQualityInspection', {
        params: { id }
      });
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        fetchUnqualifiedData();
      } else {
        ElMessage.error(`删除失败: ${response.data.message || '未知错误'}`);
      }
    } catch (error) {
      ElMessage.error('网络异常，删除失败');
      console.error(error);
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) return;

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条记录吗？删除后无法恢复。`,
    '批量删除确认',
    { type: 'warning' }
  ).then(async () => {
    const loading = ElLoading.service({ text: '删除中...' });
    try {
      let successCount = 0;
      // 循环调用删除API
      for (const id of selectedIds.value) {
        const response = await axios.delete('/api/QualityInspection/DeleteQualityInspection', {
          params: { id }
        });
        if (response.data.code === 200) successCount++;
      }

      ElMessage.success(`成功删除 ${successCount} 条，失败 ${selectedIds.value.length - successCount} 条`);
      selectedIds.value = [];
      fetchUnqualifiedData();
    } catch (error) {
      ElMessage.error('批量删除失败，请重试');
      console.error(error);
    } finally {
      loading.close();
    }
  }).catch(() => {
    ElMessage.info('已取消批量删除');
  });
};

// 页面初始化
onMounted(() => {
  fetchUnqualifiedData();
});
</script>

<style scoped>
.unqualified-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.filter-card {
  margin-bottom: 16px;
  padding: 16px;
}
.pagination-container {
  margin-top: 16px;
  text-align: right;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .filter-card .el-form {
    flex-direction: column;
    align-items: flex-start !important;
  }
  .filter-card .el-form-item {
    width: 100% !important;
    margin-bottom: 8px;
  }
}
</style>